package com.dc.util;

import com.beust.jcommander.internal.Maps;
import net.sf.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BeanToMapUtil {

    /**
     * 将javabean对象转换为map
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                Object value = beanMap.get(key);
                map.put(key + "", value);
            }
        }
        return map;
    }

    /**
     * 将map装换为javabean对象
     *
     * @param map
     * @param bean
     * @return
     */
    public static <T> T mapToBean(Map map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * 将list<Map>装换为List<javabean>对象
     *
     * @param mapList
     * @param bean
     * @return
     */
    public static <T, O> List<O> mapToBeanList(List<T> mapList, O bean) {
        List<O> result = new ArrayList<>();
        for (T map1 : mapList) {
            Object o = mapToBean((Map) map1, bean);
            result.add((O) o);
        }
        return result;
    }

}